<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // $.ajax({
    //   type: "GET",
    //   url: "url",
    //   data: "data",
    //   success: function (response) { }
    // });
    function parseData(data) {
      let str = '?'
      for (const k in data) {
        str += `${k}=${data[k]}&`
      }
      str = str.slice(0, -1)
      return str
    }


    function myajax(option) {
      let xhr = new XMLHttpRequest()
      // 这里将type转为小写，因为有的人是大写的，有的人是小写的，这里统一一下
      let type = option.type.toLowerCase()
      // 如果是post请求，就设置响应的头信息
      if (type === 'post') {
        xhr.open(option.type, option.url)
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify(option.data))
      } else {
        // 调用封装的方法，将对象转换为 ?xxx=xxx$yyy=555这种格式的字符串
        let queryStr = parseData(option.data)
        xhr.open(option.type, option.url + queryStr)
        xhr.send()
      }

      xhr.onload = function () {
        if (xhr.status === 200) {
          option.success(xhr.response)
        }
      }
      xhr.onerror = function () {
        console.log(`Network Error`);
      };
    }
    myajax({
      type: "DElETE",
      url: 'http://192.168.14.86:3000/books',
      data: {
        id: 2
      },
      // callback 回调函数 call the function when the response back
      success: function (res) {
        console.log('success:', res);
      }
    })
  </script>
</body>

</html>